'use strict';

const { getJsFiles } = require('../utils');
const router = require('koa-router')();

function regRouters(router, routerPath) {
    routerPath = routerPath || __dirname;
    let routerFiles = getJsFiles(routerPath).filter(item => item !== __filename);

    for (const routerFile of routerFiles) {
        const routes = require(routerFile);
        for (const routeName in routes) {
            if (routes.hasOwnProperty(routeName)) {
                const route = routes[routeName];
                const [rMethod, rUrl] = routeName.split(' ');
                if(router[rMethod]) {
                    router[rMethod](rUrl, route);
                } else {
                    console.log(`Invalid request method: ${rMethod}`);
                }
            }
        }
    }

    return router.routes();
}

module.exports = () => regRouters(router);